﻿using System;

class Program
{
    static void Main()
    {
        byte[] data = new byte[8];
        uint value = 0x1F4;// 0x7D0;  // 2000
        int startBit = 0;
        int bitLength = 11;

        WriteBitsIntel(data, value, startBit, bitLength);

        Console.WriteLine("写入后的数据：");
        Console.WriteLine(BitConverter.ToString(data));

        uint readValue = ReadBitsIntel(data, startBit, bitLength);
        Console.WriteLine($"读取的值：{readValue}");
    }

    // Intel（Little Endian）位序写入
    static void WriteBitsIntel(byte[] buffer, uint value, int startBit, int bitLength)
    {
        for (int i = 0; i < bitLength; i++)
        {
            int bitPos = startBit + i;
            int byteIndex = bitPos / 8;
            int bitIndex = bitPos % 8;

            if (byteIndex >= buffer.Length)
                throw new IndexOutOfRangeException();

            int bitVal = (int)((value >> i) & 0x1);

            if (bitVal == 1)
                buffer[byteIndex] |= (byte)(1 << bitIndex);
            else
                buffer[byteIndex] &= (byte)~(1 << bitIndex);
        }
    }

    // Intel（Little Endian）位序读取
    static uint ReadBitsIntel(byte[] buffer, int startBit, int bitLength)
    {
        uint val = 0;

        for (int i = 0; i < bitLength; i++)
        {
            int bitPos = startBit + i;
            int byteIndex = bitPos / 8;
            int bitIndex = bitPos % 8;

            if (byteIndex >= buffer.Length)
                throw new IndexOutOfRangeException();

            int bitVal = (buffer[byteIndex] >> bitIndex) & 0x1;
            val |= (uint)(bitVal << i);
        }

        return val;
    }
    public static string ParseResponse(string rawString)
    {
        if (string.IsNullOrEmpty(rawString))
        {
            return "错误：输入字符串为空。";
        }

        // 1. 清理控制字符（\00, \0A, \0D）
        // \0D (CR, 回车), \0A (LF, 换行), \00 (Null)
        // 使用 Trim() 清理头部和尾部的空白和空字符（如果存在）
        string cleanString = rawString.Trim(new char[] { '\r', '\n', '\0' });

        // 示例：移除字符串内部的 Null 字符（如果协议不要求保留）
        cleanString = cleanString.Replace("\0", string.Empty);

        if (string.IsNullOrEmpty(cleanString))
        {
            return "错误：字符串仅包含控制字符。";
        }

        Console.WriteLine($"清理后的字符串: [{cleanString}]"); // 打印中间结果

        // 2. 根据协议分隔符进行解析

        // 假设协议格式是：$A^0^OK#
        char[] delimiters = new char[] { '$', '^', '#' };

        string[] parts = cleanString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

        if (parts.Length >= 3 && parts[2].Trim().Equals("OK", StringComparison.OrdinalIgnoreCase))
        {
            // parts[0] 是 "A"
            // parts[1] 是 "0"
            // parts[2] 是 "OK"
            return $"解析成功！响应状态: {parts[2].Trim()}";
        }
        else if (cleanString.Contains("OK", StringComparison.OrdinalIgnoreCase))
        {
            // 如果不需要严格解析协议，只查找 "OK"
            return "解析成功！字符串中包含 OK。";
        }
        else
        {
            return "错误：未找到指定的 OK 状态。";
        }
    }
}
